<?php
/**
 * TplReader
 * - Read the template
 * - Return the source code
 * @author Do Truong Giang
 */
class TplReader {
	private $params;
	private $xmlFile;
	private $sourceCode;
	/**
	 * Constructor
	 */
	public function TplReader() {
	}
	/**
	 * read
	 * - Read xml file and return source code
	 */
	public function read($xmlFile, $params, $blockGroup = null) {
		$this->params = $params;
		$this->sourceCode = "";
		if (!is_array($blockGroup)) {
			$blockGroup = array();
		}
		$this->blockGroup = $blockGroup;
		$xml = new DomDocument();
		$xml->load($xmlFile);
		foreach ($xml->getElementsByTagName("class") as $clazz) {
			foreach (($clazz->childNodes) as $node) {
				switch ($node->nodeName) {
					case "write":
						$this->sourceCode .= self::readWriteTag($node);
						break;
					case "repeat":
						$this->sourceCode .= self::readRepeatTag($node);
						break;
				}
			}
		}
		return $this->sourceCode;
	}
	/**
	 * readWriteTag
	 * - Read a &gt;write&lt; tag
	 * - replace the content of write tag
	 * @param DomDocumentNode $node
	 */
	private function readWriteTag($node) {
		$nodeId = $node->getAttribute("id");
		if (in_array($nodeId, $this->blockGroup)) {
			return "";
		}
		$replace = $node->getAttribute("replace");
		// Extract to get all replaced variables
		$repVal = explode(",", $replace);
		// Get the content of write tag
		$content = $node->textContent;
		// remove the first LF character
		$content = substr($content, 1);
		foreach ($repVal as $rep) {
			$content = str_replace("%$rep%", $this->params[$rep], $content);
		}
		return $content;
	}
	/**
	 * readRepeatTag
	 * - Read a &gt;repeat&lt;tag
	 * - replace the content of repeat tag
	 * @param DomDocumentNode $node
	 */
	private function readRepeatTag($node) {
		$nodeId = $node->getAttribute("id");
		if (in_array($nodeId, $this->blockGroup)) {
			return "";
		}
		$sourceCode = "";
		$replace = $node->getAttribute("replace");
		// Extract to get all replaced variables
		$repVal = explode(",", $replace);
		// Get the content of repeat tag
		$content = $node->textContent;
		// remove the first LF character
		$content = substr($content, 1);
		// Now, iterate the first array to replace
		$c = count($this->params[$repVal[0]]);
		for ($i = 0; $i < $c; $i++) {
			$tmp = $content;
			foreach ($repVal as $rep) {
				$tmp = str_replace("%$rep%", $this->params[$rep][$i], $tmp);
			}
			$sourceCode .= $tmp;
		}
		return $sourceCode;
	}
}
?>